package sort;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author shkstart
 * 排序的辅助类
 * @create 2022-11-07-13:59
 */
public class SortHelper {

    //生成随机数的一个类,用法和random类似
    private static final ThreadLocalRandom random = ThreadLocalRandom.current();

    //生成一个具有n个数的随机数组，取值范围是[l,r]
    public static int[] generateRandomArray(int n,int L,int R){
        int [] ret=new int[n];
        for (int i = 0; i < n; i++) {
            ret[i] = random.nextInt(L,R);
        }

        return ret;
    }

    public static int[] generateSortedArray(int n,int times){
        int[]ret = new int[n];
        for (int i = 0; i < n; i++) {
            ret[i] = i;
        }
        //交换若干个元素的位置，就会打乱其顺序
        for (int i = 0; i < times; i++) {
            int index1 = random.nextInt(0,n-1);
            int index2 = random.nextInt(0,n-1);
            swap(ret,index1,index2);
        }
        return ret;
    }

    //判断arr是否是完全的升序集合，验证排序算法的正确性
    public static boolean isSorted(int[] arr){
        for (int i = 0; i < arr.length-1; i++) {
            if(arr[i]>arr[i+1]){
                return false;
            }

        }return true;
    }

    //根据排序名称来调用相应的排序算法来对arr做排序处理
    public static void testSort(String sortName,int[] arr) throws Exception {
        Class<SevenSort> cls = SevenSort.class;
        Method method = cls.getDeclaredMethod(sortName,int[].class);
        long start = System.nanoTime();
        method.invoke(null,arr);
        long end = System.nanoTime();
        if(isSorted(arr)){
            System.out.println(sortName+"排序完成，共耗时"+(end-start)/1000000+"ms");
        }else{
            System.out.println("shibai");
        }

    }
    public static int[] arrCopy(int[] arr){
        return Arrays.copyOf(arr,arr.length);
    }


    private static void swap(int[] ret, int index1, int index2) {
        int temp = ret[index1];
        ret[index1]= ret[index2];
        ret[index2]=temp;
    }


}
